package com.kot32.dynamicloadviewlibrary.util;


import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public abstract class DownloadTask{

    private boolean isCancelled = false;

    private void download(String url, String filePath){
        new Thread(()->{
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL mUrl = new URL(url);
                connection = (HttpURLConnection) mUrl.openConnection();
                connection.connect();
                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    onFail(String.format("response code: %d", connection.getResponseCode()));
                    return;
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                // download the file
                input = connection.getInputStream();
                output = new FileOutputStream(filePath);
                byte data[] = new byte[4096];
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        onFail("download task cancelled");
                        input.close();
                        break;
                    }
                    output.write(data, 0, count);
                }
                if (!isCancelled()) {
                    onComplete();
                }
            } catch (Exception e) {
                onFail(e.getLocalizedMessage());
            } finally {
                try {
                    if (output != null) output.close();
                    if (input != null) input.close();
                } catch (Exception e) {}
                if (connection != null) connection.disconnect();
            }
        }).start();
    }

    public void execute(String url, String filePath){
        download(url, filePath);
    }

    public void setCancelled(boolean cancelled) {
        isCancelled = cancelled;
    }

    public boolean isCancelled() {
        return isCancelled;
    }

    protected abstract void onComplete();

    protected void onFail(String errorMsg) {}
}